import React, { Component } from 'react';
import { messages } from 'share/common';
import 'styles/expense/expense-footer.scss';
import QuickReply from 'components/template/quick-reply';
import { Button, Form, Input, Modal, message } from 'antd';
import Condition from 'components/condition'
import financeAuditService from '../../financial-management/new-finance-audit/finance-audit.service';
import ModalDeleteConfirm from "../../financial-management/new-finance-audit/components/modal-delete-confirm";

const FormItem = Form.Item;
const { TextArea } = Input;
const { If } = Condition;

@Form.create()
class ExpenseFooter extends Component {
  static contextTypes = {
    nowExpenseDataSource: React.PropTypes.array,
    expenseReport: React.PropTypes.object,
  };

  state = {
    isShowBigTextArea: false,
    attachmentOIDs: []
  };

  handleSubmit = (e) => {
    e.preventDefault();
    const { expenseReport, nowExpenseDataSource } = this.context;
    this.props.form.validateFieldsAndScroll(async (err, values) => {
      try {
        await this.handleVerify(values);
        if (nowExpenseDataSource.length === 1) {
          ModalDeleteConfirm.open({
            visible: true,
            info: expenseReport,
            onOk: deleteBagRelation => this.confirmReject(values.reason, deleteBagRelation)
          });
        } else {
          this.confirmReject(values.reason, false);
        }
      }
      catch (e) {
      }
    });
  };


  confirmReject = async (reason, deleteBagRelation) => {
    const { form: { setFieldsValue }, invoiceOID } = this.props;
    const { expenseReport: { expenseReportOID } } = this.context;
    const { attachmentOIDs } = this.state;
    let params = {
      approvalTxt: reason,
      expenseReportOID,
      invoiceOIDs: [invoiceOID],
      needChargeBack: false,
      attachmentOIDs,
      deleteBagRelation
    };
    this.setState({ rejectLoading: true });
    try {
      const res = await financeAuditService.rejectExpense(params);
      let { failReason, failNum } = res.data;
      this.setState({ rejectLoading: false });
      setFieldsValue({ reason: '' });
      if (res.status === 200 && failNum === 0) {
        message.success(messages('common.operate.success')/*操作成功*/);
        this.props.handleReject();
      } else {
        let firstError = failReason[Object.keys(failReason)[0]];
        message.error(`${messages('common.operate.filed')/*操作失败*/}, ${firstError}`);
      }
    }
    catch (e) {
    }
    this.setState({ rejectLoading: false });
  };

  handleVerify = async (values) => {
    await new Promise((res, rej) => {
      if (!values.reason) {
        message.error(messages('expense-1.key690')/*请输入驳回理由*/);
        rej();
      }
      if (values.reason.length > 500) {
        message.error(messages('expense-1.key691')/*最多输入500个字符*/);
        rej();
      }
      res();
    });
  };

  handleImageUpload = attachments => {
    this.setState({ attachmentOIDs: attachments.map(a => a.attachmentOID) });
  };

  handleAutoSize = (isFocus) => {
    if (isFocus) {
      if (this.timer) {
        clearTimeout(this.timer);
      }
      this.setState({
        isShowBigTextArea: true
      });
    } else {
      this.timer = setTimeout(()=>{
        this.setState({
          isShowBigTextArea: false
        });
      },1000);
    }
  };

  handleChangeType = (e) => {
    this.props.handleBack(e, { isSwitchOld: true });
  };

  afterSelectTag = () => {
    this.reasonInput.focus();
  };

  afterChange = () => {
    let values = this.props.form.getFieldsValue();
    if(values.reason && values.reason.length > 500) {
      this.setState({
        inputError: true,
        errorMessage: messages('common.max.characters.length',{arg1: 500})/*最多输入{arg1}个字符*/
      });
    } else {
      this.setState({
        inputError: false,
        errorMessage : ''
      })
    }
  };

  render() {
    const { isShowBigTextArea, rejectLoading } = this.state;
    const { form: { getFieldDecorator }, isReject } = this.props;
    return (
      <section   className={this.classNames({
        'expense-footer': true,
        'expense-footer-big': isShowBigTextArea
      })}>
        <div className="expense-footer-form">
          <Form name="expense-footer-form" layout={'inline'} onSubmit={this.handleSubmit}>
            <If value={isReject}>
              <FormItem>
                {getFieldDecorator('reason')(
                  <QuickReply
                    afterSelectTag={this.afterSelectTag}
                    afterChange={this.afterChange}
                    handleImageUpload={this.handleImageUpload}
                    params={{
                      audit: true,
                      withAttachments: true
                    }}
                  >
                    <TextArea
                      className={this.classNames({
                        'expense-footer-textarea': true,
                        'expense-footer-textarea-big': isShowBigTextArea
                      })}
                      ref={node => this.reasonInput = node}
                      onBlur={() => this.handleAutoSize(false)}
                      onFocus={() => this.handleAutoSize(true)}
                    />
                  </QuickReply>
                )}
              </FormItem>
              <FormItem>
                <Button type="danger" loading={rejectLoading} htmlType="submit">{messages('common.reject')/*驳回*/}</Button>
              </FormItem>
            </If>
            <FormItem>
              <Button type="default" loading={rejectLoading} onClick={this.handleChangeType}>{messages('expense-1.key692')/*切换旧版*/}</Button>
            </FormItem>
          </Form>
        </div>
        <div className="expense-footer-back">
          <Button loading={rejectLoading} onClick={this.props.handleBack} type="default">{messages('common.back')/*返回*/}</Button>
        </div>
      </section>
    );
  }
}

ExpenseFooter.propTypes = {};

export default ExpenseFooter;
